define(['moment', 'module/moduleMobile/program/mobile06/StockIn.service'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', 'config', '$StockInService', '$document','$calculater',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, config, $StockInService, $document,$calculater) {
            $scope.init = function(){
                $scope.status_list = [
                    {name: $filter('translate')('mobile06.do_flag_0'), value:'0'},
                    {name: $filter('translate')('mobile06.do_flag_1'), value:'1'},
                ];
                $scope.do_flag = '0';
                $scope.type = '0'; // 0:良品 1:不良品
                $scope.barcode_wo_no = '';
                $scope.barcode_plot_no = '';
                $scope.warehouseInfo = {
                    plot_info_detail: []
                };
            };

            $scope.back = function(){
                $rootScope.changeProgram($stateParams.data.parent, {data: {}}, true);
            };

            $scope.itemCheck = function(item){
                item.checked = !item.checked;
            };
            //M#97324 入庫數量添加小數位數
            $scope.check_storage_qty = function (event,item) 
            {
                var target = event.currentTarget;
                $calculater.open(function(num,calcDialog)
                {
                    item.storage_qty = (+num).toFixed(4);
                    angular.element(target).removeClass('is-focus');
                    calcDialog.hide();
                },function(calcDialog)
                {
                    angular.element(target).removeClass('is-focus');
                    calcDialog.hide();
                },
                {
                    defaultNum : item.storage_qty,
                    decimal : true
                });
            }
            //取得工單編號
            $scope.loadWoNoList = function () {
                var page_mode;
                if($scope.type == '0'){
                    page_mode = 20;
                } else if($scope.type == '1'){
                    page_mode = 21;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord:50,
                    header: [
                        {label:$filter('translate')('common.queryList.wo_c'), code:'page_no'}
                    ],
                    setCondition:function(conditions){
                        if($scope.barcode_wo_no != '')
                            conditions.push({column_name:'C.MoNo', query_mode:'2', value: $scope.barcode_wo_no, merge_condition_model:'AND' });
                        return conditions;
                    },
                    selectCode: $scope.barcode_wo_no,
                    confirm : function(selectItem){
                        $scope.barcode_wo_no = selectItem.page_no;
                        input_wo_no_callback();
                    }
                });
            };

            //取得生產批號清單
            $scope.loadPlotNoList = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: '20-1',
                    pageRecord: 50,
                    header: [
                        {label:$filter('translate')('common.queryList.plot_no'), code:'page_no'}
                    ],
                    setCondition:function(conditions){
                        if($scope.barcode_wo_no != '')
                            conditions.push({column_name:'B.MoNo', query_mode:'2', value: $scope.barcode_wo_no, merge_condition_model:'AND' });
                        if($scope.barcode_plot_no != '')
                            conditions.push({column_name:'B.BASELOTNO', query_mode:'2', value: $scope.barcode_plot_no, merge_condition_model:'AND' });
                        return conditions;
                    },
                    selectCode: $scope.barcode_plot_no,
                    confirm : function(selectItem){
                        $scope.barcode_plot_no = selectItem.page_no;
                        input_plot_no_callback();
                    }
                });
            };

            $scope.confirm = function(){
                var plot_info_detail = $scope.warehouseInfo.plot_info_detail[$scope.do_flag] || [];
                var selectedList = $filter('filter')(plot_info_detail, {checked: true});
                var going_down = false; //檢測入庫數量是否大於原有數量的卡控
                selectedList.forEach(function(item){
                    item.storage_qty = Number(item.storage_qty)
                    item.qty = Number(item.qty);
                    if(item.storage_qty > item.qty){
                        going_down=true;
                        return;
                    }
                });
                if(selectedList.length > 0){
                    if(going_down){
                        $scope.$root.showAlert($filter('translate')('mobile06.msg.storage_qty_oversize'));
                    }else{
                        // 20201222 modify by WeiTing for M#72157 - 檢查選取的資料是否都是相同的倉庫和儲位(搬到手機版)。
                        var sameInventoryAndStorage = isCheckSameInventoryAndStorage($scope.warehouseInfo.plot_info_detail); 
                        $StockInService.init({
                            type: '0',
                            do_flag: $scope.do_flag,
                            sameInventoryAndStorage: sameInventoryAndStorage,
                            selectedList: selectedList,
                            callback: function(){
                                warehousePlotInfoGet_Imp($scope.do_flag, function(){});
                            }
                        });
                    }
                } else {
                    $scope.$root.showAlert($filter('translate')('mobile06.msg.plot_detail_empty'));
                }
            };

            // 20201222 modify by WeiTing for M#72157 - 檢查選取的資料是否都是相同的倉庫和儲位(搬到手機版)。
            function isCheckSameInventoryAndStorage(selectedList){
                var checkList = {
                    inventoryNo: '', // 倉庫
                    storageSpacesNo: '', // 儲位
                    isStopInventory: false, // 不同倉庫時，停止判斷
                    isStopStorage: false // 不同儲位時，停止判斷
                };

                if(selectedList && selectedList.length > 1){
                    for(var i = 0; i < selectedList.length > 0; i++){
                        if(i < selectedList.length - 1){
                            // 檢查選取的資料的倉庫是否都相同
                            if(selectedList[i].inventoryno && !checkList.isStopInventory){
                                if(selectedList[i].inventoryno === selectedList[i+1].inventoryno){
                                    checkList.inventoryNo = selectedList[i].inventoryno;
                                } else {
                                    checkList.inventoryNo = '';
                                    checkList.isStopInventory = true;
                                }
                            } else {
                                checkList.inventoryNo = '';
                                checkList.isStopInventory = true;
                            }

                            // 檢查選取的資料的儲位是否都相同
                            if(selectedList[i].storage_spaces_no && !checkList.isStopStorage){
                                if(selectedList[i].storage_spaces_no === selectedList[i+1].storage_spaces_no){
                                    checkList.storageSpacesNo = selectedList[i].storage_spaces_no;
                                } else {
                                    checkList.storageSpacesNo = '';
                                    checkList.isStopStorage = true;
                                }
                            } else {
                                checkList.storageSpacesNo = '';
                                checkList.isStopStorage = true;
                            }
                        }
                    }
                } else {
                    if(selectedList[0].inventoryno){
                        checkList.inventoryNo = selectedList[0].inventoryno;
                    } 
                    if(selectedList[0].storage_spaces_no){
                        checkList.storageSpacesNo = selectedList[0].storage_spaces_no;
                    } 
                }

                return checkList;
            }

            $scope.QRCodeScanner = function(target_id){
                $scope.$root.OpenScanner({
                    after : function(result){
                        if(target_id == 'input_wo'){
                            $scope.barcode_wo_no = result.text;
                            input_wo_no_callback();
                        }else if(target_id == 'input_plot'){
                            $scope.barcode_plot_no = result.text;
                            input_plot_no_callback();
                        }
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation : 'portrait'
                });
            };

            $scope.changeTab = function(tab_index){
                $scope.status_list.forEach(function(data, index){
                    if(index == tab_index){
                        data.select = true;
                        $scope.do_flag = data.value;
                    } else {
                        data.select = false;
                    }
                });
            };

            $scope.getTabSize = function(do_flag){
                var plot_info_detail = [];
                if($scope.warehouseInfo.plot_info_detail){
                    plot_info_detail = $scope.warehouseInfo.plot_info_detail[do_flag] || [];
                }
                return plot_info_detail.length;
            };

            // 工單編號
            var element_wo_no = document.getElementById('input_wo');
            $scope.input_wo_no = function(event){
                if(event.keyCode == 13){
                    element_wo_no.blur();
                    input_wo_no_callback();
                } else {
                    $scope.barcode_wo_no = $scope.barcode_wo_no||'';
                }
            };

            // 生產批編號
            var element_plot_no = document.getElementById('input_plot');
            $scope.input_plot_no = function(event){
                if(event.keyCode == 13){
                    element_plot_no.blur();
                    input_plot_no_callback();
                } else {
                    $scope.barcode_plot_no = $scope.barcode_plot_no||'';
                }
            };

            function input_wo_no_callback(){
                //檢查輸入的對不對
                var barcode_wo_no = $scope.barcode_wo_no;
                if(barcode_wo_no && barcode_wo_no.length > 0){
                    beforeSearch(function(){
                        search(function(){
                            // $scope.barcode_plot_no = '';
                        });
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('mobile06.msg.wo_no_empty'));
                    element_wo_no.focus();
                }
            }

            function input_plot_no_callback(){
                //檢查輸入的對不對
                var barcode_plot_no = $scope.barcode_plot_no;
                if(barcode_plot_no && barcode_plot_no.length > 0){
                    beforeSearch(function(){
                        search(function(){
                            // $scope.barcode_plot_no = '';
                        });
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('mobile06.msg.plot_no_empty'));
                    element_plot_no.focus();
                }
            }

            function beforeSearch(callback){
                var plot_info_detail = $scope.warehouseInfo.plot_info_detail[$scope.do_flag];
                var isChecked = false;
                if(plot_info_detail && plot_info_detail.length > 0){
                    for(var i = 0; i < plot_info_detail.length; i++){
                        if(plot_info_detail[i].checked){
                            isChecked = true;
                            break;
                        }
                    }
                }
                if(isChecked){
                    $scope.$root.showConfirm($filter('translate')('mobile06.msg.keep_on_hold'), function(dialog){
                        dialog.hide();
                        $scope.warehouseInfo.plot_info_detail = [];
                        if (callback)
                            callback();
                    }, function(dialog){
                        dialog.hide();
                    });
                } else{
                    if (callback)
                        callback();
                }
            }

            function search(callback){
                warehousePlotInfoGet_Imp('0', function(){
                    warehousePlotInfoGet_Imp('1', function(){
                        if($scope.warehouseInfo.plot_info_detail[0].length > 0 || $scope.warehouseInfo.plot_info_detail[1].length > 0){
                            if (callback)
                                callback();
                        } else{
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        }
                    });
                });
            }

            function warehousePlotInfoGet_Imp(do_flag, callback){
                warehousePlotInfoGet(do_flag, function(data){
                    $scope.warehouseInfo.plot_info_detail[do_flag] = data || [];
                    $scope.warehouseInfo.plot_info_detail[do_flag].forEach(function (detail) {
                        detail.checked = true;
                    });
                    if (callback)
                        callback();
                });
            }

            //取得待入庫資料
            function warehousePlotInfoGet(do_flag, callback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.warehouse_plot_info_get',
                    content: {
                        wo_no: $scope.barcode_wo_no || '',
                        plot_no: $scope.barcode_plot_no || '',
                        type: $scope.type,
                        item_no: '',
                        do_flag: do_flag
                    },
                    success: function (data) {
                        // 20200514 數量修改 設定 modify by Oliver for M#70010 分量入庫
                        data.warehouse_plot_info_get.forEach(function(item){
                            item.storage_qty = item.qty;
                        })
                        callback(data.warehouse_plot_info_get);
                    }
                });
            }
        }
    ];
});
